package com.abe.abetest.widget;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.abe.abetest.R;

public class BottomView extends PopupWindow {
    private Activity activity;
    private View contentView;

    public BottomView(Fragment fragment, View contentView) {
        this(fragment.getActivity(), contentView);
    }

    public BottomView(Activity activity, View contentView) {
        super(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        this.activity = activity;
        this.contentView = contentView;
        setFocusable(true);// 取得焦点
        //点击外部消失
        setOutsideTouchable(true);
        //设置可以点击
        setTouchable(true);
        //进入退出的动画，指定刚才定义的style
        setAnimationStyle(R.style.popWindowAnimStyle);
        setOnDismissListener(() -> backgroundAlpha(activity, 1));
        contentView.setOnKeyListener((v, keyCode, event) -> {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                if (isShowing()) {
                    dismiss();
                    return true;
                }
            }
            return false;
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha bgAlpha(//0.0-1.0)
     */
    private void backgroundAlpha(Activity activity, float bgAlpha) {
        if (activity == null) return;
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);
    }

    public void show() {
        if (activity == null) return;
        backgroundAlpha(activity, 0.7f);
        //从底部显示
        showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }
}